/**
 * TodoStore
 *
 */

import { types, Instance, cast } from 'mobx-state-tree';
import Utils from '../../Common/Utils';
import TodoForm from './TodoForm';
import TodoItem from './TodoItem';

export enum TodoFilterType {
  All = 'All',
  Active = 'Active',
  Completed = 'Completed'
}

const Todo = types
  .model('todo')
  .props({
    filterType: types.optional(types.string, Utils.store('todo_filterType') || TodoFilterType.All),
    adderForm: types.optional(TodoForm, {}),
    editorForm: types.optional(TodoForm, {}),
    list: types.optional(types.array(TodoItem), Utils.store('todo_list') || [])
  })
  .views(self => ({
    get doneList() {
      return self.list.filter(item => item.isCompleted);
    },
    get activeList() {
      return self.list.filter(item => !item.isCompleted);
    },
    get showList() {
      switch (self.filterType) {
        case TodoFilterType.All:
          return self.list;
        case TodoFilterType.Active:
          return this.activeList;
        case TodoFilterType.Completed:
          return this.doneList;
        default:
          return self.list;
      }
    },
    get todoLength() {
      return this.showList.length;
    },
    get isAllCompleted() {
      return !!self.list.length && self.list.length === this.doneList.length;
    }
  }))
  .actions(self => ({
    // 添加待办项
    addTodoItem() {
      if (self.adderForm.valid) {
        self.list.push({
          id: Utils.uuid(),
          title: self.adderForm.trimVal,
          isCompleted: false
        });
        self.adderForm.reset();
        Utils.store('todo_list', self.list);
      }
    },
    // 删除待办项
    deleteTodoItem(id: string) {
      const index = self.list.findIndex(item => item.id === id);
      if (index >= 0) {
        self.list.splice(index, 1);
      }
      Utils.store('todo_list', self.list);
    },
    // 更新待办项
    updateTodoItem() {
      if (self.editorForm.valid) {
        const currItem = self.list.find(item => item.id === self.editorForm.targetItemId);
        if (currItem) {
          currItem.title = self.editorForm.trimVal;
        }
        self.editorForm.reset();
        Utils.store('todo_list', self.list);
      }
    },
    // 筛选待办项
    setFilterType(filterType: string) {
      self.filterType = filterType;
      Utils.store('todo_filterType', self.filterType);
    },
    // 完成所有待办项
    switchAllCompleted(allCompleted?: boolean) {
      if (typeof allCompleted !== 'boolean') {
        allCompleted = !self.isAllCompleted;
      }
      self.list.forEach(item => item.toggleComplete(allCompleted));
      Utils.store('todo_list', self.list);
    },
    // 清空所用选中项
    clearCompletedItems() {
      self.list = cast(self.list.filter(item => !item.isCompleted));
      Utils.store('todo_list', self.list);
    }
  }));

export default Todo;
export type TodoInstance = Instance<typeof Todo>;
